from urllib.parse import parse_qs

import pymysql


def login(environ):
    with open('templates/login.html', 'rb') as f:
        data = f.read()
    return data


def index(environ):
    with open('templates/index.html', 'rb') as f:
        data = f.read()
    return data


def favicon(environ):
    with open('templates/favicon.ico', 'rb') as f:
        data = f.read()
    return data


def reg(environ):
    with open('templates/reg.html', 'rb') as f:
        data = f.read()
    return data


def timer(environ):
    import datetime
    now = datetime.datetime.now().strftime('%y-%m-%d %X')
    return now.encode('utf8')


def auth(environ):
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except ValueError:
        request_body_size = 0

    request_body = environ['wsgi.input'].read(request_body_size)
    data = parse_qs(request_body)
    # TypeError: 'NoneType' object is not subscriptable
    if data.get(b"user"):
        user = data.get(b"user")[0].decode("utf8")
    else:
        user = ''
    if data.get(b"pwd"):
        pwd = data.get(b"pwd")[0].decode("utf8")
    else:
        pwd = ''

    # 连接数据库
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='web')  # db：库名
    # 创建游标
    cur = conn.cursor()
    sql = "select * from userinfo WHERE NAME ='%s' AND PASSWORD ='%s'" % (user, pwd)
    cur.execute(sql)

    if cur.fetchone():

        f = open("templates/backend.html", "rb")
        data = f.read()
        data = data.decode("utf8")
        return data.encode("utf8")

    else:
        print("OK456")
        return b"user or pwd is wrong"
